<?php

namespace Xrfg\Api\Trading\Spot\Rules;

use Illuminate\Support\Facades\Cache;
use Xrfg\Core\Trading\Spot\Models\Order;
use Xrfg\Core\Trading\Spot\Models\Pair;

class Validator
{
    /**
     * 价格小数位验证.
     *
     * @param $attribute
     * @param $value
     * @param $parameters
     * @param $validator
     *
     * @return bool
     */
    public function priceDecimals($attribute, $value, $parameters, $validator)
    {
        $order_type = $parameters[0];
        if (Order::TYPE_MARKET == $order_type) { // 市价单不用验证
            return true;
        }

        $symbol = $parameters[1];
        $pair = Cache::remember('table:trading_spot_pairs:'.$symbol, now()->addHour(), function () use ($symbol) {
            return Pair::where('symbol', $symbol)->first();
        });
        if (!$pair) {
            return true;
        }

        $arr = explode('.', rtrim($value, '0'));
        if (sizeof($arr) > 1) {
            $decimal = end($arr);
            if (strlen($decimal) > $pair->coin_decimals) {
                return false;
            }
        }

        return true;
    }

    /**
     * 数量小数位验证.
     *
     * @param $attribute
     * @param $value
     * @param $parameters
     * @param $validator
     *
     * @return bool
     */
    public function numberDecimals($attribute, $value, $parameters, $validator)
    {
        $symbol = $parameters[1];
        $pair = Cache::remember('table:trading_spot_pairs:'.$symbol, now()->addHour(), function () use ($symbol) {
            return Pair::where('symbol', $symbol)->first();
        });
        if (!$pair) {
            return true;
        }

        $arr = explode('.', rtrim($value, '0'));
        if (sizeof($arr) > 1) {
            $decimal = end($arr);
            if (strlen($decimal) > $pair->market_decimals) {
                return false;
            }
        }

        return true;
    }
}
